from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, render, get_object_or_404
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.auth.forms import UserCreationForm
from bets.models import Game, Tournament, GameField, Team, Player, UserBet
from django.shortcuts import redirect
from django.http import Http404


##################### UTILS BEGIN ########################
        
def __get_top__(g, count):
    teams = sorted(Team.objects.all().filter(game=g), key=lambda x: x.rating, reverse=True)
    players = []
    for team in teams:
        players += team.player_set.all()
    players = sorted(players, key=lambda x: x.rating, reverse=True)
    return { 'top_teams'   : teams[:count],
             'top_players' : players[:count] }

##################### UTILS  END ########################

def search_view(request):
    try:
        context = { 'teams' : Team.objects.all().filter(name=request.GET['q']),
                    'players' : Player.objects.all().filter(name=request.GET['q']),
                    'value' : request.GET['q'] }
    except (KeyError):
        raise Http404
    
    return render(request, 'bets/search_results.html', context, context_instance=RequestContext(request))

def bet_view(request, game_name, tour_id):
    g = get_object_or_404(Game, pk=game_name)
    bets_list = g.gamefield_set.all()
    context = { 'bets_list' : bets_list, 
                'tour_id'   : tour_id,
                'game'      : g }
    context.update(__get_top__(g, 5))
    return render(request, 'bets/bets_list.html', context, context_instance=RequestContext(request))

def game_view(request):
    context = { 'game_list' : Game.objects.all() }
    return render(request, 'bets/games_list.html', context, context_instance=RequestContext(request)) 

def tournament_view(request, game_name):
    g = get_object_or_404(Game, pk=game_name)
    tournament_list = Tournament.objects.all().filter(game=g)
    context = { 'tour_list' : tournament_list,
                'game'      : g }
    context.update(__get_top__(g, 5))
    return render(request, 'bets/tournament_list.html', context, context_instance=RequestContext(request)) 

def team_view(request, game_name, bet, tour):
    t = get_object_or_404(Tournament, pk=tour)
    b = get_object_or_404(GameField, pk=bet)
    g = get_object_or_404(Game, pk=game_name)
    teams_list = Team.objects.all().filter(tournament=t)
    gold = request.user.get_profile().gold

    l = {'list': teams_list,
         'gold' : gold,
         'site_name' : "Teams",
         'name' : "team",
         'bet' : b,
         'tour_id' : tour }
    l.update(__get_top__(g, 5))    

    if request.method == "GET":
        gold = request.user.get_profile().gold
        return render_to_response('bets/teams_list.html', l, context_instance=RequestContext(request))
    else:
        if b.type == "team":
            try:
                obj = Team.objects.all().get(pk=request.POST['team'])
            except (KeyError, Team.DoesNotExist):
                l['error_message'] = "You didn't select a team."
                return render(request, 'bets/teams_list.html', l, context_instance=RequestContext(request))
            bet_value = obj.name
        elif b.type == "player":
            try:
                obj = Player.objects.all().get(pk=request.POST['player'])
            except (KeyError, Player.DoesNotExist):
                l['error_message'] = "You didn't select a player."
                return render(request, 'bets/teams_list.html', l, context_instance=RequestContext(request))
            bet_value = obj.name
        elif b.type == "yes/no":
            try:
                bet_value = request.POST['yes/no']
            except (KeyError):
                l['error_message'] = "You didn't choosed."
                return render(request, 'bets/teams_list.html', l, context_instance=RequestContext(request))       

        bet_gold = request.POST['user_bet']
        
        try:
            bet_gold = int(bet_gold)
        except ValueError:
            l['error_message'] = "Please, enter correct count of money."
            return render(request, 'bets/teams_list.html', l, context_instance=RequestContext(request))
        
        if bet_gold <= 0:
            l['error_message'] = "Please, enter correct count of money."
            return render(request, 'bets/teams_list.html', l, context_instance=RequestContext(request))            
        
        if bet_gold > gold:
            l['error_message'] = "You have not such money."
            return render(request, 'bets/teams_list.html', l, context_instance=RequestContext(request))
        
        request.user.get_profile().gold -= int(bet_gold)
        request.user.get_profile().save()
        
        userbet = UserBet(user=request.user, bet=b, tournament=t, value=bet_value, gold=int(bet_gold))
        userbet.save()

        return redirect('bets:bet_success_view', game_name=g.name, tour_id=tour)
    
def bet_success_view(request, game_name, tour_id):
    g = get_object_or_404(Game, pk=game_name)
    context = { 'game_name' : game_name,
                'tour_id'   : tour_id }
    context.update(__get_top__(g, 5))  
    return render(request, 'bets/bet_success.html', context, context_instance=RequestContext(request)) 

def balance_view(request):
    context = { 'balance' : request.user.get_profile().gold }
    return render(request, 'bets/balance.html', context, context_instance=RequestContext(request)) 

def player_profile_view(request, game_name, player_id):
    player = Player.objects.all().get(pk=player_id)
    context = { 'player' : player }
    g = get_object_or_404(Game, pk=game_name)
    tour = player.team.tournament_set.all()
    if len(tour) > 0:
        context['tour_first'] = tour[0]
        context['tour'] = tour[1:]
    context.update(__get_top__(g, 5))
    return render(request, 'bets/player_profile.html', context)

def team_profile_view(request, game_name, team_id):
    team = Team.objects.all().get(pk=team_id)
    context = { 'team' : team }
    g = get_object_or_404(Game, pk=game_name)
    tour = team.tournament_set.all()
    players = team.player_set.all()
    if len(players) > 0:
        context['player_first'] = players[0]
        context['player'] = players[1:]    
    if len(tour) > 0:
        context['tour_first'] = tour[0]
        context['tour'] = tour[1:]
    context.update(__get_top__(g, 5))    
    return render(request, 'bets/team_profile.html', context)

def login_view(request):
    from django.contrib.auth.views import login
    from django.contrib import auth
    
    register_form = UserCreationForm()

    if request.method == "GET":
        return login(request, extra_context={'register_form': register_form, 'betuser' : request.user})
    else:
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            # Correct password, and the user is marked "active"
            auth.login(request, user)
            # Redirect to a game page.
            return HttpResponseRedirect(reverse('bets:game_view'))
        else:
            # TODO Show an error page
            return login(request, extra_context={ 'register_form'  : register_form,
                                                  'betuser'        : request.user, 
                                                  'error_msg'      : 'Invalid login or password'} )

def logout_view(request):
    from django.contrib import auth
    auth.logout(request)
    return HttpResponseRedirect(reverse('bets:login_view'))

def register_view(request):
    register_form = UserCreationForm()
    if request.method == "GET":
        return render_to_response('bets/registration_form.html', {'form': register_form},
                                  context_instance=RequestContext(request))
    else:
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect(reverse('bets:login_view'))
        else:
            return render_to_response('bets/registration_form.html',
                                       { 'form'      : register_form, 
                                         'error_msg' : 'Error: Invalid fields'}, 
                                      context_instance=RequestContext(request))        
